package com.zhiyou100.springbootreidsquartz.service.imp;

import com.zhiyou100.springbootreidsquartz.mapper.IActorMapper;
import com.zhiyou100.springbootreidsquartz.pojo.Actor;
import com.zhiyou100.springbootreidsquartz.service.IActorService;
import com.zhiyou100.springbootreidsquartz.util.RedisUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

@Service(value = "actorService")
public class ActorServiceImpl implements IActorService {
    /*引入mapper*/
    @Resource
    private IActorMapper actorMapper;
    /*引入redis工具类*/
    @Resource
    private RedisUtils redisUtils;
    /*查询全部*/
    @Override
    public List<Actor> queryAll() {
        //定义老师list集合
        List<Actor> actors = new ArrayList<>();


        /*从redis中拿数据*/
        //查询所有键
        Set<String> keys = redisUtils.keys("actor:id:*");
        //如果键里有值就从键中拿
        if (keys.size()>0){
            //遍历所有的键
            for (String key : keys) {
                Integer id =(Integer) redisUtils.hget(key,"id");
                String name =(String) redisUtils.hget(key,"name");
                String desc = (String) redisUtils.hget(key, "desc");
                actors.add(new Actor(id,name,desc));
            }
        }
        else {
            //存入Redis
            /*从MySQL中拿数据,调用mapper层*/
            actors = actorMapper.selectList(null);
            //向redis中存一份
            for (Actor actor : actors) {
                HashMap<String,Object> map = new HashMap<>();
                map.put("id",actor.getId());
                map.put("name",actor.getName());
                map.put("phone",actor.getDesc());
                redisUtils.hmset("actor:id:"+actor.getId(),map);

            }
        }

        return actors;
    }
}
